import React from 'react';
import {Spin, Tree} from 'antd';
import { OptionType } from '@/types/common';
import {DataNode, EventDataNode} from "rc-tree/lib/interface";

interface CustomTreeProps{
  value?: (string | number)[];
  className?: string;
  onChange?: (value:(string | number)[])=>void;
  list:OptionType[];
  loading?: boolean|undefined;
  renderTitle?: (record:any)=>React.ReactNode;
}

interface CustomTreeState{
  selectedKeys?: (string | number)[];
}

export default class CustomTree extends React.Component<CustomTreeProps,CustomTreeState> {

  static defaultProps={
    list:[]
  }

  state={
    selectedKeys:this.props.value||[],
  }

  static getDerivedStateFromProps(nextProps: CustomTreeProps) {
    if ('value' in nextProps) {
      return { selectedKeys: nextProps.value || [] };
    }
    return null;
  }

  onSelect = (value: (string | number)[],info:{
      event: 'select';
      selected: boolean;
      node: EventDataNode;
      selectedNodes: DataNode[];
      nativeEvent: MouseEvent;
    }) => {
    if (!('value' in this.props)) {
      this.setState({ selectedKeys:value });
    }
    const { onChange } = this.props;
    if (onChange) {
      onChange(value);
    }
  };

  renderTree = (options:OptionType[]):any[] =>{

    const {renderTitle}=this.props;

    return options.map(option => {
        if (option.children) {
          return {
            key:option.id,
            title:renderTitle?renderTitle(option):option.name,
            children:this.renderTree(option.children)
          }
        }
        return {
          key:option.id,
          title:renderTitle?renderTitle(option):option.name,
        }
      })
  }

  render() {

    const { loading,list,className } = this.props;
    const { selectedKeys } = this.state;

    return (
      <Spin spinning={!!loading}>
        <Tree
          className={className}
          treeData={this.renderTree(list)}
          selectedKeys={selectedKeys}
          onSelect={this.onSelect}
        />
      </Spin>
    );
  }
}

